package joc.internal;

import joc.internal.compiler.StaticCall;
import joc.internal.util.ObjectMapper;

public class SingletonConditionCache {
	private static final ObjectMapper<String, ConditionWrapper> conditionCache = new ObjectMapper<String, ConditionWrapper>();

	public static final StaticCall saveConditionIfNotExists = new StaticCall(SingletonConditionCache.class,
			"saveConditionIfNotExists");
	public static final StaticCall activateCondition = new StaticCall(SingletonConditionCache.class,
			"activateCondition");
	public static final StaticCall getCondition = new StaticCall(SingletonConditionCache.class, "getCondition");
	public static final StaticCall reserveConditionIfPossible = new StaticCall(SingletonConditionCache.class,
			"reserveConditionIfPossible");

	public static synchronized void saveConditionIfNotExists(Object obj, String key, Object condition) {
		if (!conditionCache.contains(obj, key)) {
			conditionCache.put(obj, key, new ConditionWrapper(condition));
		}
	}

	public static synchronized Object getCondition(Object obj, String key) {
		return conditionCache.get(obj, key).getCondition();
	}

	public static synchronized void activateCondition(Object obj, String key) {
		conditionCache.get(obj, key).setActive(true);
	}

	public static synchronized boolean reserveConditionIfPossible(Object obj, String key) {
		if (conditionCache.get(obj, key).isActive()) {
			conditionCache.get(obj, key).setActive(false);
			return true;
		}
		return false;
	}
}
